package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderList;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {


	@Autowired
    OrderMapper orderMapper;

	@Autowired
    OrderItemMapper orderItemMapper;

	@Autowired
    OrderShippingMapper orderShippingMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

	@Autowired
    StockMapper stockMapper;


	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);

		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);

		}
		return response;
	}

	@Override
	public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
		CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
		try {
			// 参数校验
			request.requestCheck();

			int itemStatus = 2;

			Order order = new Order();
			order.setOrderId(request.getOrderId());
			order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
			order.setUpdateTime(new Date(System.currentTimeMillis()));

			// 更改订单状态
			int arrowLine = orderMapper.updateByPrimaryKeySelective(order);
			int arrowLine2 = orderItemMapper.updateStockStatus(itemStatus, request.getOrderId());

			// 判断是否更改成功
			if(arrowLine == 0 || arrowLine2 == 0){
				throw new RuntimeException();
			}
			// 更改库存
			Example example = new Example(OrderItem.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("orderId",request.getOrderId());
			List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

			for (OrderItem orderItem : orderItems) {
				Stock stock = new Stock();
				// 给将orderItem中的属性赋值给stock
				BeanUtils.copyProperties(orderItem,stock);
				stockMapper.updateStock(stock);
			}
			//返回信息
			cancelOrderResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
			cancelOrderResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.cancelOrder occur Exception :"+e);
			ExceptionProcessorUtils.wrapperHandlerException(cancelOrderResponse,e);
		}
		return cancelOrderResponse;
	}

	@Override
	public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
		DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
		try {
			// 参数校验
			request.requestCheck();

			//进行删除操作
			int arrowLine = orderMapper.deleteByPrimaryKey(request.getOrderId());
			Example example = new Example(OrderItem.class);
			example.createCriteria().andEqualTo("orderId",request.getOrderId());
			int arrowLine2 = orderItemMapper.deleteByExample(example);
			int arrowLine3 = orderShippingMapper.deleteByPrimaryKey(request.getOrderId());

			// 判断是否删除成功
			if(arrowLine == 0 || arrowLine2 == 0 || arrowLine3 == 0){
				throw new RuntimeException();
			}
			// 返回信息
			deleteOrderResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
			deleteOrderResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

		}catch (Exception e){
			log.error("OrderCoreServiceImpl.deleteOrder occur Exception :"+e);
			ExceptionProcessorUtils.wrapperHandlerException(deleteOrderResponse,e);
		}

		return deleteOrderResponse;
	}

}
